package masterjava.common.server.gwt.rpc.controller;

import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import masterjava.common.logging.ServerLogger;
import masterjava.common.server.ContextHolder;
import masterjava.common.shared.state.StateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GwtRpcController extends RemoteServiceServlet implements Controller {

    protected ServerLogger logger = ServerLogger.get(this.getClass());

    @Autowired
    private ServletContext servletContext;

    @Override
    public ServletContext getServletContext() {
        return servletContext;
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        long startHandleTime = System.currentTimeMillis();
        try {
            logger.debug("RPC request has been received");
            doPost(request, response);
            return null;
        } catch (DataAccessException e) {
            throw new StateException("DB exception", e);
        } finally {
            logger.debug("RPC request was handled in " + (System.currentTimeMillis() - startHandleTime) + " ms");
        }
    }

    @Override
    public String processCall(String payload) throws SerializationException {
        ContextHolder.setContext(perThreadRequest.get());
        return super.processCall(payload);
    }

    @Override
    protected void doUnexpectedFailure(Throwable t) {
        logger.error(t.getMessage(), t);
        super.doUnexpectedFailure(t);
    }
}
